<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="宠物名称" prop="recipeName">
        <el-input v-model="queryParams.recipeName" placeholder="请输入宠物名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="分类" prop="categoryId">
        <el-tree-select
          v-model="queryParams.categoryId"
          :data="categoryOptions"
          :props="{ value: 'categoryId', label: 'categoryName', children: 'children' }"
          value-key="categoryId"
          placeholder="请选择分类"
          clearable
          style="width: 180px"
        />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="queryParams.gender" placeholder="请选择性别" clearable style="width: 180px">
          <el-option v-for="dict in genderOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建人" prop="createBy">
        <el-input
          v-model="queryParams.createBy"
          placeholder="请输入创建人"
          clearable
          @keyup.enter="handleQuery"
          style="width: 180px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 180px">
          <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recipeList" @selection-change="handleSelectionChange">
      <el-table-column label="宠物ID" align="center" prop="recipeId" v-if="false" />
      <el-table-column label="宠物名称" align="center" prop="recipeName" :show-overflow-tooltip="true" />
      <el-table-column label="分类" align="center" prop="categoryId">
        <template #default="scope">
          {{ getCategoryName(scope.row.categoryId) }}
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center" prop="description" :show-overflow-tooltip="true" />
      <el-table-column label="封面图片" align="center" prop="coverImage" width="100">
        <template #default="scope">
          <el-image
            v-if="scope.row.coverImage"
            :src="scope.row.coverImage"
            style="max-height: 50px; max-width: 50px"
            :preview-src-list="[scope.row.coverImage]"
          />
          <span v-else>无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="年龄" align="center" prop="age">
        <template #default="scope">{{ scope.row.age }} 岁</template>
      </el-table-column>
      <el-table-column label="性别" align="center" prop="gender">
        <template #default="scope">
          {{ scope.row.gender === 1 ? '公' : scope.row.gender === 2 ? '母' : '未知' }}
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" width="100" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="scope.row.status === '1' ? 'warning' : scope.row.status === '2' ? 'info' : 'success'">
            {{ scope.row.status === '1' ? '待领养' : scope.row.status === '2' ? '已确定领养' : '已领养' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button type="text" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button type="text" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改宠物对话框 -->
    <recipe-dialog
      ref="dialogRef"
      :title="title"
      :form="form"
      :category-options="categoryOptions"
      :status-options="statusOptions"
      @success="handleSuccess"
    />
  </div>
</template>

<script setup>
import { listRecipe, getRecipe, delRecipe, addRecipe, updateRecipe } from '@/api/pet/recipe'
import { treeCategory } from '@/api/pet/category'
import { ref, getCurrentInstance, onMounted } from 'vue'
import RecipeDialog from './components/RecipeDialog.vue'

const { proxy } = getCurrentInstance()

const recipeList = ref([])
const loading = ref(true)
const showSearch = ref(true)
const total = ref(0)
const title = ref('')
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const dialogRef = ref()

// 状态数据字典
const statusOptions = ref([
  { value: '1', label: '待领养' },
  { value: '2', label: '已确定领养' },
  { value: '3', label: '已领养' }
])

// 性别选项
const genderOptions = ref([
  { value: 1, label: '公' },
  { value: 2, label: '母' }
])

// 分类选项
const categoryOptions = ref([])

// 根据分类ID获取分类名称
function getCategoryName(categoryId) {
  // 使用递归函数在分类树中查找指定ID的分类
  function findCategory(categories, id) {
    for (const category of categories) {
      if (category.categoryId == id) {
        return category
      }
      if (category.children && category.children.length > 0) {
        const found = findCategory(category.children, id)
        if (found) return found
      }
    }
    return null
  }

  const category = findCategory(categoryOptions.value, categoryId)
  return category ? category.categoryName : categoryId
}

// 获取分类树
function getCategoryTree() {
  treeCategory().then(response => {
    // 将扁平结构转换为树形结构
    const flatData = response.data
    categoryOptions.value = convertToTree(flatData)
  })
}

// 将扁平数组转换为树形结构
function convertToTree(data) {
  if (!data || data.length === 0) return []

  // 创建一个映射表用于快速访问节点
  const map = {}
  const result = []

  // 第一步：将所有节点加入映射表，并初始化children数组
  data.forEach(item => {
    map[item.categoryId] = { ...item, children: [] }
  })

  // 第二步：构建树形结构
  data.forEach(item => {
    const node = map[item.categoryId]
    if (item.parentId === 0) {
      // 顶级节点直接加入结果数组
      result.push(node)
    } else {
      // 子节点加入到父节点的children数组
      if (map[item.parentId]) {
        map[item.parentId].children.push(node)
      }
    }
  })

  return result
}

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  recipeName: '',
  categoryId: '',
  gender: '',
  status: '',
  createBy: ''
})

// 表单参数
const form = ref({
  recipeId: '',
  recipeName: '',
  categoryId: '',
  description: '',
  coverImage: '',
  petContent: '',
  age: 0,
  gender: 1,
  status: '1',
  remark: ''
})

/** 查询宠物列表 */
function getList() {
  loading.value = true
  listRecipe(queryParams.value).then(response => {
    recipeList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.$refs['queryForm']?.resetFields()
  handleQuery()
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.recipeId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  form.value = {
    recipeId: '',
    recipeName: '',
    categoryId: '',
    description: '',
    coverImage: '',
    petContent: '',
    age: 0,
    gender: 1,
    status: '1',
    remark: ''
  }
  title.value = '添加宠物'
  dialogRef.value.visible = true
}

/** 修改按钮操作 */
function handleUpdate(row) {
  const _recipeId = row.recipeId || ids.value[0]
  getRecipe(_recipeId).then(response => {
    form.value = response.data
    title.value = '修改宠物'
    dialogRef.value.visible = true
  })
}

/** 提交成功回调 */
function handleSuccess(formData) {
  if (formData.recipeId) {
    updateRecipe(formData).then(response => {
      proxy.$modal.msgSuccess('修改成功')
      getList()
    })
  } else {
    addRecipe(formData).then(response => {
      proxy.$modal.msgSuccess('新增成功')
      getList()
    })
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _recipeIds = row.recipeId || ids.value
  proxy.$modal
    .confirm('是否确认删除宠物编号为"' + _recipeIds + '"的数据项？')
    .then(function () {
      return delRecipe(_recipeIds)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

// 页面加载时获取列表数据和分类数据
onMounted(() => {
  getList()
  getCategoryTree()
})
</script>
